import type { PiniaPluginContext } from 'pinia';

/*
 * @title: 持久化缓存状态
 * @Description:
 * @Author: JZT.饶慧勇
 * @Date: 2025-05-29 19:32:56
 * @LastEditors: JZT.饶慧勇
 * @LastEditTime: 2025-06-06 10:49:59
 */
export function uniPersist(context: PiniaPluginContext) {
  const {
    store,
    options: { persist = false }
  } = context;
  if (!persist) return;

  // 从存储中读取数据
  const storedState = uni.getStorageSync(`pinia_${store.$id}`);
  if (storedState) {
    store.$patch(JSON.parse(storedState));
  }
  // 订阅 store 变化
  store.$subscribe((mutation, state) => {
    // 根据配置存储指定state数据
    let obj = {};
    const persistenceOptions = Array.isArray(persist) ? persist : [null];
    for (const key of persistenceOptions) {
      if (key === null) {
        obj = state;
        break;
      } else {
        obj[key] = state[key];
      }
    }
    uni.setStorageSync(`pinia_${store.$id}`, JSON.stringify(obj));
  });
}
